<?php


namespace Api\Controller;


/** 
 * 积分商城
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

class GiftController extends PublicController 
{

	/** 
	 * [获取热门的商品]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	public function hot($limit = 3)
	{
		$map = ['status' => 1];
		$gifts = service('Gift')->where($map)->limit($limit)->order('hot desc')->select();
		$this->format($gifts, true);
		$this->list_success($gifts);
	}

	// 获取推荐
	public function recommend($limit = 3)
	{
		$map = ['status' => 1, 'is_recomd' => 1];
		$gifts = service('Gift')->where($map)->limit($limit)->order('create_time desc')->select();
		$this->format($gifts, true);
		$this->list_success($gifts);
	}

	/** 
	 * [详细信息]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	public function show($id = 0)
	{
		if (!$id)
		{
			return $this->param_error();
		}
		$gift = event('Gift')->detail($id);
		$this->format($gift);
		$this->success('', $gift);
	}


	/** 
	 * [使用兑换]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	public function exchange($id = 0)
	{
		if (!$id)
		{
			$this->param_error();
		}
		$token = I('appToken', '', 'strip_tags');
		$uid = $this->getUid($token);
		if (!$uid)
		{
			$this->login_error();
			// $uid = 1;
		}
		$event = event('Gift');
		G('begin');
		$res = $event->exchange($uid, $id);
		G('end');
		// echo G('begin','end', 10).'s|';
		if ($res == false)
		{
			return $this->error($event->error['err'], $event->error['info']);
		}
		return $this->success('成功获得', ['code' => $res]);
	}


	protected function format(&$gifts = [],  $complex = false)
	{
		static $game_options;
		if (!$game_options) $game_options = event('Game')->getOptions();
		if (!$complex) $gifts = [$gifts];
		foreach ($gifts as $key => &$value) {
			$value['thumb'] = $value['pics'][0];
			isset($game_options[$value['game_id']]) && $value['game']  = ['id' => $value['game_id'], 'name' => $game_options[$value['game_id']]];
		}
		if (!$complex) $gifts = $gifts[0];
		return $gifts = field_filter($gifts, ['id', 'game', 'type', 'thumb', 'name', 'content', 'stock', 'hot'], $complex, ['thumb']);
	}


}